<?php
require_once 'Zend/Db/Table/Abstract.php';

class User extends Zend_Db_Table_Abstract {
	
	const NAME = "name";
	const EMAIL = "email";
	const MOBILE = "mobile";
	
	protected $_name = 'user';
	protected $_primary = 'id';
	
	protected $_dependentTables = array(
		'Advertisement',
		'Message',
		'UserComment',
		'UserRecommendation',
		'AdvertisementResponse'
	);
	
	/**
	 * Find user by id.
	 * 
	 * @param $id
	 * @return user
	 */
	public function findById($id) {
		return $this->find($id)->current();
	}
	
	/**
	 * Add user, if user is already exist, then just return it.
	 * 
	 * @param $data
	 * @return return user
	 */
	public function addUser($data) {
		$user = $this->findByUnique($data['email']);
		if (!isset($user)) {
			$user = $this->createRow($data);
			$user->save();
		} else {
			if (!empty($data["name"])) {
				$user->name = $data["name"];
			}
			if (empty($user->original_mobile)) {
				$user->original_mobile = $data["mobile"];
			} else {
				if (!empty($data["mobile"])) {
					$user->mobile = $data["mobile"];
				}
			}
			$user->save();
		}
		return $user;
	}
	
	/**
	 * Find user by unique.
	 * 
	 * @param $email
	 */
	public function findByUnique($email) {
		$select = $this->select()->where('upper(email)=upper(?)', trim($email));
		return $this->fetchRow($select);
	}
	
    /**
	 * Update user last access date.
	 * 
	 * @param $id
	 * @param $lastAccess
	 */
	public function updateLastAccess($id, $lastAccess) {
		$user = $this->findById($id);
        $user->last_access = $lastAccess;
        $user->save();
	}
	
	/**
	 * Get user comments by given user.
	 * 
	 * @param $user
	 */
	public static function getComments($user) {
		$table = new User();
        $select = $table->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
        ->setIntegrityCheck(false)
        ->from(array("m"=>"message"), array("message"=>"m.body", "messageId"=>"m.id", "messageCreated"=>"m.created", "status"=>"m.status"))
        ->join(array("uc"=>"user_comment"), "uc.message_id=m.id")
        ->join(array("targetUser"=>"user"), "uc.target_user=targetUser.id", array("targetUserId"=>"targetUser.id", "targetUserName"=>"targetUser.name", "targetUserEmail"=>"targetUser.email"))
        ->join(array("messageUser"=>"user"), "m.user_id=messageUser.id", array("messageUserId"=>"messageUser.id", "messageUserName"=>"messageUser.name", "messageUserEmail"=>"messageUser.email"))
        ->where("targetUser.id=?", $user->id)
        ->orWhere("messageUser.id=?", $user->id)
        ->group("messageId")
        ->order("messageCreated desc");
        
        return $table->fetchAll($select);
	}
}
?>